<?php
namespace app\api\controller;

use think\Controller;
use think\Db;
use app\api\controller\Pinyin;

class Users extends Controller
{
    protected function _initialize(){
        parent::_initialize();
    }

    public function publish_kouling(){
        if($this->request->isPost()){
            $data = $this->request->param();
            $userInfo = Db::name('third_user')->field('user_id,remainder')->where('openid',$data['openid'])->find();
            if(!$userInfo){
                return json(['msg'=>'未登录,无法操作']);
            }else{
                //有余额先扣除余额
                if($userInfo['remainder'] > 0){
                    if($userInfo['remainder'] - ($data['reward'] + $data['sevice_price'])  == 0){
                        //余额刚好扣除赏金加服务费
                        $yu_e = ['remainder'=>0.00];
                    }else if($userInfo['remainder'] - ($data['reward'] + $data['sevice_price'])  < 0){
                        //余额不够扣,先减除余额在支付差额
                        $cha_e = $userInfo['remainder'] - ($data['reward'] + $data['sevice_price']);
                        return json(['msg'=>'需补差额','status'=>2,'result'=>abs($cha_e)]);
                    }else{
                        //余额足够扣赏金的情况
                        $yu_e = ['remainder'=>$userInfo['remainder'] - ($data['reward'] + $data['sevice_price'])];
                    }
                    $update_remainder = Db::name('third_user')->where('user_id',$data['uid'])->update($yu_e);
                    if($update_remainder){
                        $data['create_time'] = date('Y-m-d H:i:s');
                        $pinyin = new Pinyin();
                        $data['pinyin'] = $pinyin->encode($data['kouling'],'head');
                        $total = $data['reward'];
                        $min=0.01;//每个人最少能收到0.01元 
                        $num_reward = '';
                        for ($i=1;$i<$data['num'];$i++) 
                        {
                            $safe_total=($total-($data['num']-$i)*$min)/($data['num']-$i);//随机安全上限 
                            $money=mt_rand($min*100,$safe_total*100)/100; 
                            $total=$total-$money; 
                            $num_reward .= $money.',';
                        } 
                        $num_reward .= $total;
                        $data['num_reward'] = $num_reward;
                        $result = Db::name('users_kouling')->insertGetId($data);
                        return json(['msg'=>'添加成功','status'=>1,'result'=>$result]);
                    }
                }else{
                    //没有余额
                    return json(['msg'=>'没余额','status'=>3,'result'=>$data['reward'] + $data['sevice_price']]);
                }
            }
        }
    }

    public function payment_publish_kouling(){
        if($this->request->isPost()){
            $data = $this->request->post();
            //能走到这，余额都为0
            $yu_e = ['remainder'=>0.00];
            Db::name('third_user')->where('user_id',$data['uid'])->update($yu_e);
            $data['create_time'] = date('Y-m-d H:i:s');
            $pinyin = new Pinyin();
            $data['pinyin'] = $pinyin->encode($data['kouling'],'head');
            $total = $data['reward'];
            $min=0.01;//每个人最少能收到0.01元 
            $num_reward = '';
            for ($i=1;$i<$data['num'];$i++) 
            {
                $safe_total=($total-($data['num']-$i)*$min)/($data['num']-$i);//随机安全上限 
                $money = mt_rand($min*100,$safe_total*100)/100; 
                $total=$total-$money; 
                $num_reward .= $money.',';
            } 
            $num_reward .= $total;
            $data['num_reward'] = $num_reward;
            $result = Db::name('users_kouling')->insertGetId($data);
            return json(['msg'=>'添加成功','status'=>1,'result'=>$result]);
        }
    }

    public function get_user_qrcode($id){
        $koulingInfo = Db::name('users_kouling')->where('id',$id)->find();
        $access_token = $this->getAccessToken();
        
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;

        $postfields = [
            'scene'=>'id='.$id,
            'page'=>'pages/index/index',
            // 'auto_color'=>true,
            // 'line_color'=>['r'=>'98','g'=>'185','b'=>'0']
        ];
        $post_json = json_encode($postfields);
        $result = httpRequest($url,'POST',$post_json);
        // dump(base64_encode($result));exit();
        // return $result;

        return json(['koulingInfo'=>$koulingInfo,'qrcode'=>base64_encode($result)]);
    }

    public function getAccessToken(){
        $wechatMsg = Db::name('wx_user')->find();

        //判断是否过了缓存期
        $expire_time = $wechatMsg['web_expires'];
        if($expire_time > time()){
            return $wechatMsg['web_access_token'];
        }

        $appid = $wechatMsg['appid'];
        $appsecret = $wechatMsg['appsecret'];
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;

        $json_str = httpRequest($url);
        $return = json_decode($json_str,true);
        if ($return === false) {
            return false;
        }
        $web_expires = time() + 7000; // 提前200秒过期
        Db::name('wx_user')->where('id',$wechatMsg['id'])->update(['web_access_token'=>$return['access_token'], 'web_expires'=>$web_expires]);

        return $return['access_token'];
    }

    public function getMoneyReward(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $userTakeRewardMsg = [];
            //获取剩余赏金和剩余红包个数
            $surplus = Db::name('users_kouling')->where('id',$data['koulingId'])->find();
            $moneyArr = explode(',',$surplus['num_reward']);
            $money = $moneyArr[0];//领取的红包放进变量
            unset($moneyArr[0]);  //删除已领取红包
            $num_reward = implode(',',$moneyArr);
            $update_data = [
                'num_reward'=>$num_reward,
                'rest'=>$surplus['rest']+1,
            ];
            $update = Db::name('users_kouling')->where('id',$data['koulingId'])->update($update_data);
            if($update){
                $userTakeRewardMsg = [
                    'k_id'=>$data['koulingId'],
                    'openid'=>$data['userOpenId'],
                    'header_url'=>$data['headerImgUrl'],
                    'nickname'=>$data['nickName'],
                    'sex'=>$data['sex'],
                    'receive_reward'=>$money,
                    'receive_time'=>date('Y-m-d H:i:s'),
                    'radio_path'=>$data['radioPath'],
                ];
                Db::name('receive')->insert($userTakeRewardMsg);//保存用户领取红包记录加了触发器,会修改用户余额和总额
                $result = Db::name('receive')->where('k_id',$data['koulingId'])->select();
                $reward = Db::name('receive')->where('openid',$data['userOpenId'])->where('k_id',$data['koulingId'])->find();
                return json(['current_reward'=>$reward,'receive_list'=>$result]);
                // dump($userTakeRewardMsg);
            }
        }
    }

    public function isUserTakeReward(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $map['k_id'] = ['eq',$data['id']];
            $map['openid'] = ['eq',$data['openId']];
            $result = Db::name('receive')->where($map)->find();
            if($result){
                //已经领取过赏金
                return json(['status'=>1,'msg'=>'已领取赏金','usertakereward'=>$result]);
            }else{
                //未领取过赏金
                //判断是否还有赏金
                $is_reward = Db::name('users_kouling')->field('num_reward')->where('id',$data['id'])->find();
                if($is_reward['num_reward'] == ''){
                    return json(['status'=>3,'msg'=>'赏金都被领完了']);
                }else{
                    return json(['status'=>0,'msg'=>'未领取赏金']);
                }
            }
        }
    }

    //查询用户发出红包数
    public function queryUserSend(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $result = Db::name('users_kouling')->where('openid',$data['openid'])->select();
            $record = Db::name('users_kouling')->field('sum(reward) as total_reward,sum(num) as total_num')->where('openid',$data['openid'])->select();
            return json(['userSend'=>$result,'total'=>$record[0]]);
        }
    }

    //查询用户收到赏金
    public function queryUserGet(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $result = Db::name('receive')->where('openid',$data['openid'])->select();
            $record = Db::name('receive')->field('sum(receive_reward) as total_receive_reward,count(id) as total_receive_num')->where('openid',$data['openid'])->select();
            return json(['userGet'=>$result,'total'=>$record[0]]);
        }
    }

    //查询用户余额
    public function queryUserRemainder(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $result = Db::name('third_user')->where('openid',$data['openid'])->value('remainder');
            return json(['remainder'=>$result]);
        }
    }


}